/**
 * App页面，html页面，小程序页面，DIY设计器 
 */
Rsd.define('Rsd.tool.AppDesigner', {
    extend: 'Rsd.container.Dialog',
    requires: [
        'Rsd.tool.PropertiesEditor',
        'Rsd.container.Form',
        'Rsd.form.Button',
        'Rsd.form.Text',
        'Rsd.form.ComboBox',
        'Rsd.form.Image',
        'Rsd.control.Grid', 
        'Rsd.control.MenuList',
        'Rsd.container.Simulator',
        'Rsd.control.Tree',
        'Rsd.control.Svg'
    ],
    width:'100%',
    height:'100%', 
    closeBtn:false,
    draggable:false,
    header:{ 
        position:'top',
        space:0,
        xtype:'container',
        height:60,
        width:'100%', 
        header:{
            content:'',
            position:'left',
            width:30
        }, 
        style:{
            color:'#ffffff',
            lineHeight:'55px',
            backgroundColor:'rgba(0,0,0,0.55)'
        },
        layout:'hbox', 
        items: [
            { 
                xtype: 'label', 
                label:false, 
                text: '页面设计' , 
                style:{fontSize:'120%',fontWeight:600}
            }, 
            {
                header: false,
                flex: 180,
                layout: 'hbox',
                items: [  ]
            },  
           
            {
                xtype: 'button',
                margin:'0 15 0 15',
                text: '预 览',
                handler: '_btn_preview',
                height: 35,
                width: 90,
                style: {
                    color: '#ffffff',
                    backgroundColor: '#04bb13ff',
                    borderRadius: '5px'
                }
            },
            {
                xtype: 'button',
                 margin:'0 15 0 15',
                text: '保存到草稿',
                handler: '_btn_save',
                height: 35,
                width: 90,
                style: {
                    color: '#ffffff',
                    backgroundColor: '#0484f5',
                    borderRadius: '5px'
                }
                //#
            },
            {
                xtype: 'button',
                 margin:'0 15 0 15',
                width: 120,
                height: 35,
                text: '保存并发布',
                handler: 'btn_save_and_publish',
                style: {
                    color: '#ffffff',
                    backgroundColor: '#050de9',
                    borderRadius: '5px'
                }
            },
            { flex: 100 },
            {
                xtype: 'button',
                text: '重 置',
                handler: 'btn_reset',
                height: 35,
                width: 90,
                style: {
                    color: '#ffffff',
                    backgroundColor: '#b84e06',
                    borderRadius: '5px'
                }
            },  
            {
                xtype: 'button',
                margin:'0 30 0 15',
                height: 35,
                text: '退 出',
                handler: 'btn_close',
                style: {
                    color: '#ffffff',
                    backgroundColor: '#680404',
                    borderRadius: '5px'
                }
            },
        ]
    },
    bodyStyle:{
        minHeight:850,
        overflow:'auto'
    },
    cls:'',
    style:{ 
        minWidth:1600,
        overflow:'auto'
    }, 
    layout: {type:'hbox',align:'center',content:'start start'},
    items:[ 
        //0;page list
        {
            xtype: 'grid', 
            margin:'0 15 0 15',
            height:'95%',
            flex:20,
            label:{
                xtype:'combobox',
                width:'90%', 
                height:40,
                margin:'5 0 5 0',
                position:'top', 
                //"style":{backgroundColor:'rgba(31, 116, 227, 0.247059)'}, 
                config:{
                    label: {
                        space:0,
                        content: '文档类型',
                        height:30,
                        width:100,
                        "style": {
                            color:'#000',
                            fontWeight: 300, 
                            fontSize: '120%'
                        }
                    },  
                    width:'100%',
                    height:40,  
                    nullText: '--请选择类型--',
                    dataSource:[
                        {text:'商场首页'},
                        {text:'专题活动'},
                        {text:'会员中心'},
                        {text:'商品详情'},
                        {text:'商品分类'}
                    ],
                    textChanged:'page_type_changed',
               } 
            },
            overflow:'auto',
            "style":{
                 border:'1px #756d6d solid',
                borderRadius:'5px',
                backgroundColor:'rgba(214,214,214,0.2)'
            },
            border:false,
            columns:
            [
                {xtype:'index',text:'序号',width:40,fixed:true},
                {text:'名称',width:160,dataIndex:'name'},
                {text:'类型',width:80,dataIndex:'value',editable:true},
                {dataIndex:'op',width:5,fixed:true}
            ],
            dataSource:
            [
                {name:'春节档首页'},
                {name:'元霄档首页'},
                {name:'2-14情人节首页'},
                {name:'3-8节首页'}
            ],
            rowdblclick:'doc_rowdblclick'
        }, 
        //1:control list
        {
            xtype:'menu-list', 
            height:'94%',
            width:100, 
            label:{ 
                    content:'页面元素',
                    "style":
                    {
                        textAlign:'center',
                        color:'#000',
                        fontWeight:500, 
                        fontSize:'120%'
                    }
            }, 
            ctrlStyle:{
                backgroundColor:'#transparent',
                lineHeight:50,
                zIndex:9999,
                overflow:'auto'
            },
            style:{
                border:'1px #756d6d solid',
                borderRadius:'5px'
            },
            cls:'x-list-view-toolbar',  
            layout:"vbox",
            itemClick:'btn_add',
            "itemStyle":{"height":'50px',"width":'100%',"float":'left',"textAlign":'left'}
        }, 
        //2:simulator
        {
            xtype:'simulator',
            margin:'0 15 0 15',
            title:'',
            height:'95%',
            width:420, 
            style:{position:'relative'}, 
            onChanged:'buildTree',
            onSelectChanged:'loadCtrlProperty'
        },  
        //3:doc tree
        {
            xtype:'tree',
             margin:'0 15 0 0',
            height:'94%',  
            flex:20,
            label:{ 
                xtype:'link',
                label:{
                    space:0, 
                    content:'文档结构',
                    align:'left',
                    width:200,
                    "style":{
                        color:'#000',
                        fontWeight:500, 
                        fontSize:'120%'
                    },
                },
                space:10, 
                height:40,
                width:'100%',  
                "ctrlStyle":{
                    height:'40px', 
                    color:'#fff',
                    textAlign:'center',
                    backgroundColor:'#397cd4'
                }, 
                text:'刷 新', 
                handler:'btn_refresh'
            },
            "style":{
                border:'1px #756d6d solid',
                borderRadius:'5px',
                backgroundColor:'rgba(214,214,214,0.2)'
            },   
            nodeStyle:{height:35,lineHeight:35},
            nodeClick:'tree_select_ctrl',
            showRoot:false,
            showLine:false,
            //border:false
        },
         //4:properties editor
         {
            xtype: 'properties-editor', 
            width:400,
            height:'91%', 
            overflow:'auto',
            "style":{
                right:20,
                backgroundColor:'#d6d6d633'
            }, 
            beforeClose:'properties_before_close',
            onChanged:'pr_on_changed'
        },

    ],
    ctrlConfig:[
        {
            text:'表 单',
            icon:'default.123',
            config:
            {
                xtype:'form',
                draggable:true,
                text:'Form',
                border:true,
                width:'100%',
                height:100
            }
        },
        {
            text:'方 框',
            icon:'default.123',
            config:{
                xtype:'container',
                draggable:true,
                text:'Box',
                border:true,
                width:'100%',
                height:100
            }
        },
        {
            text:'图 片',
            icon:'default.146',
            config:{
                xtype:'image',
                draggable:true,
                text:'Image',
                border:false,
                view:false,
                width:'100%',
                height:150,
                src:'http://image.redmicro.cn/wxapp/xchief/emptyImg.png'
            }
        },
        {
            text:'文 本',
            icon:'default.6',
            config:{
                xtype:'label',
                draggable:true,
                label:{content:'标题',position:'top',width:'100%',align:'center'},
                text:'文字信息',
                width:'100%',
                height:100,
                mulitiLine:true
            }
        },
        {
            text:'连 接',
            icon:'default.5',
            config:{xtype:'link', width:'100%',draggable:true,text:'点击跳转'}
        },
        {
            text:'按 钮',
            icon:'default.14',
            config:{xtype:'button',draggable:true,text:'提交按钮'}
        }, 
        {text:'搜 索',config:{}},
        {text:'新 闻',config:{}},
        {
            text:'幻灯片',
            config:{}
        },
        {text:'导 航',config:{}},
        {text:'菜 单',config:{}},
        {text:'商 品',config:{}},
        {text:'广 告',config:{}}
    ],
    saveApi:null,
    getApi:null,
    listApi:null,
    previewApi:null,
    publishApi:null,
    page:{},
    autoLoad:true, 
    /*
    * */
    constructor: function AppDesigner(config) {
        config = config || {};
        this.apply(config); 
    },
    /**
     * 
     */
    onAfterInit:function onAfterInit()
    {
        this.callParent(); 
    },
    /**
     * 
     * @returns 
     */
    beforeClose:function beforeClose()
    {
        Rsd.showPopup('编辑器退出，退出检查是否已保存数据');
        return false;
    },
    /*
    * 加载数据
    * */
    load:function load(data) {
 
         var me = this; 
        this.header.content.items[1].setElStyle('ctrl',{backgroundColor:'#ddf3fe'},);
        //page列表数据 和分类数据
        this.items[0].loadData();
        
        var svg = Rsd.create('Rsd.data.SvgLoader',{});
        svg.load(Rsd.getRedjsUrl('/resources/svg/icon.js'));

        //加载开发组件 
        var  btns = Rsd.create('Rsd.data.Menu',{});
        for(var i in this.ctrlConfig)
        {
            btns.addItem(this.ctrlConfig[i]);
        } 

        setTimeout(function(){
            var ctrls_list = me.items[1];
            ctrls_list.loadData(btns);
        },1000);
        
        //加载页面
       
        var simulator = me.items[2];
        setTimeout(function () {

            var _doc = simulator.getDocument();
            if(_doc != null)
            {
                var link = _doc.createElement('link');
                link.type = 'text/css';
                link.rel = 'stylesheet';
                link.href = Rsd.getRedjsHost() + 'resources/css/Rsd.css';
                var head = _doc.getElementsByTagName('head')[0];
                head.appendChild(link);
                me.header.content.items[0].setText(me.page.Title);
                simulator.setDocumentTitle(me.page.Title);
            }
            simulator.loadData(data||me.page);

           

        },100);

        setTimeout(function(){
            me.buildTree(true); 
        },300);

    },
    /**
     * 
     */ 
    _btn_preview:function _btn_preview()
    {
        Rsd.showPopup('预览');
    },
    /**
     * 
     */
    _btn_save:function _btn_save()
    {
        var simulator = this.items[2];
        var page = simulator.getDocConfig(true);  
        this.log('save page in app designer',this);
        page.id = this.page.id;
        this.funApplyByIOC(this.saveApi,[page]); 
    },
    /**
     * 
     */
    btn_save_and_publish:function()
    {
        var simulator = this.items[2];
        var page = simulator.getDocConfig(true); 
        page.id = this.page.id;
        this.funApplyByIOC(this.saveApi,[page]); 
        this.funApplyByIOC(this.publishApi,[page])
    },
     /**
      * 
      */
    btn_reset:function btn_reset()
    {
        Rsd.showPopup('重置');
    },
    /**
     * 
     */
    btn_close:function btn_close()
    { 
        this.close();
    },
    /**
     * 
     */
    page_type_changed:function page_type_changed(sender,e)
    {
        this.funApplyByIOC(this.listApi,[sender.selectedItem]);  
    },
    /** 
     * 添加控件
    */
    btn_add:function btn_add(item) {
        var me = this;
        //console.log(item);
        var _menu = item.menu;
        if(_menu.config=== undefined || _menu.config==null)
        {
            Rsd.alert('控件['+_menu.text +']未设置config');
            return;
        }
        if(Rsd.isEmpty(_menu.config.xtype))
        {
            Rsd.alert('控件['+_menu.text +']config属性未设置xtype');
            return;
        }
        var simulator = this.items[2];
        var _ctrl = simulator.addControl(_menu.config);

       
        setTimeout(function () {
            me.buildTree();

            me.loadCtrlProperty(_ctrl, null);

        },20);

    },
    /**
     * 
     */
    btn_refresh:function btn_refresh()
    {
        this.buildTree();
    },
    /**
     * 构建文档结构树
     */
    buildTree:function buildTree(selectedRoot) {

        //debugger;
        var simulator = this.items[2];
         var _doc = simulator.getDocConfig();
        if(!_doc)
        {
            return;
        }
         var _tree = this.items[3];

         var _nodes = [];
         _nodes.push({text: _doc.id+'(' + _doc.title+')',id:_doc.id ,  autoExpanded: true, dynamic: true, tag: _doc.element})

         var _list = _doc.items;

         for (var i = 0; i < _list.length; i++) {
             var _obj = _list[i];
             var _config = {
                 id: _obj.id,
                 pid: _obj.parent,
                 text: _obj.id + '[' + _obj.xtype + ']',
                 title: _obj.title,
                 autoExpanded: true,
                 dynamic: true,
                 tag: _obj.element
             };
             _nodes.push(_config);
         }

         _tree.loadData(_nodes);

         if(selectedRoot)
         { 
            this.loadCtrlProperty(_doc.element,{});
         } 
        

    },
    /**
     * 文档结构中 选择则控件
     * @param {*} node 
     * @param {*} event 
     */
    tree_select_ctrl:function tree_select_ctrl(node,event)
    {    
        if(node.tag)
        {
             
            this.loadCtrlProperty(node.tag,event);
           
        }else
        {
            Rsd.showMessage('对象不存在');
        }

    },
    /**
     * 展示控件属性值
     * @param {docment or control} sender 
     * @param {*} event 
     */
    loadCtrlProperty:function loadCtrlProperty(sender, event) {

        var simulator = this.items[2];
        var _tree = this.items[3];
        var _pr_editor = this.items[4]; //属性编辑控件

        _pr_editor.element = sender; 
        var _config = simulator.getControlConfig(sender); 
        _pr_editor.load(_config);

        //select tree node 
      
        _tree.clearSelected();
        //debugger;
        _tree.selectNode(sender.id);
 
        simulator.clearSelected();
        simulator.selectControl(sender.id);
       
    },
 
    /**
    *属性值发生改变
    * */
    pr_on_changed:function pr_on_changed(sender,event) {

        var simulator = this.items[2];
        var _pr_editor = this.items[4];

         if(Rsd.isType(_pr_editor.element ,HTMLDocument))
         {
             if(sender.name == 'title')
             {
                 var title = sender.getValue();
                 simulator.setDocumentTitle(title);
                 if(title !=  this.title)
                 {
                    this.title = title; 
                    this.header.content.items[0].setText(this.title);
                 }
                 
             }
             if(sender.name == 'indexFile')
             {
                 simulator.setDocumentIndex(sender.getValue());
             }
              
         }
         else
         {
             _pr_editor.element[sender.name] = sender.getValue();
             _pr_editor.element.doLayout();

         }
        this.buildTree();
    },
    properties_before_close:function properties_before_close()
    { 
        var _pr_editor = this.items[4];
        _pr_editor.closeCancel = true;
        _pr_editor.setElStyle('dom',{
            width:'60px',
            height:'200px',
            overflow:'hidden',
            top:'100px',
            right:'0px'
        });
        return false;
    }

});